# Alexander F. Gazmararian
# afg2@princeton.edu

# Load packages
library(tidyverse)
library(modelsummary)
library(lmtest)
library(sandwich)
library(kableExtra)
library(margins)

# Load functions
source("code/fun/book_theme.r")
source("code/fun/savefig.r")
source("code/fun/fix_txt.r")
source("code/fun/coefnames4tables.r")

# Load CivicPulse data
cp <- readRDS("data/CivicPulse_Public.rds")

# Specify models

## NOTE: the following variables are only in the restricted access data (see README.txt): biden2020 + Census_area_college + log(Census_area_population) + Census_area_urban
f.base <- y ~ Age_cat + Woman + College + Minority_bin + PartySummary + Gov_type + biden2020 + Sample + Census_area_college + log(Census_area_population) + Census_area_urban
f.base.slim <- y ~ Age_cat + Woman + College + Minority_bin  + Gov_type +  Sample

# Estimate models
m <- list()
m[[1]] <- lm(Clawback_scale ~ clawtreat + transptreat + Sample, cp)
m[[2]] <- lm(update(f.base.slim, Clawback_scale ~ clawtreat + transptreat + .), cp)

#m[[3]] <- lm(update(f.base, Clawback_scale ~ clawtreat + transptreat + .), cp)

# Create online appendix table ----
file <- "tables/ch8/ols_clawback_civicpulse.txt"
modelsummary(
  m,
  stars = c("*"=.1,"**"=.05,"***"=.01),
  coef_map = coefnames,
  vcov = "HC2",
  gof_map = c("nobs", "adj.r.squared"),
  escape = FALSE,
  output = "latex"
) %>%
  cat(., file = file)
fix_txt(file)

# Create Figure 8.7 ----
p.clawback<-
  cp %>%
  mutate(Clawback = factor(Clawback, ordered = TRUE,
                           levels = rev(c("Very likely", "Somewhat likely", "Somewhat unlikely", "Very unlikely")))) %>%
  mutate(clawtreat = ifelse(clawtreat == 1, "Clawback", "No clawback")) %>%
  filter(!is.na(Clawback)) %>%
  group_by(clawtreat, Clawback) %>%
  count() %>%
  group_by(clawtreat) %>%
  mutate(pct = prop.table(n)) %>%
  ggplot(aes(x=Clawback,y=pct,fill=clawtreat,color=clawtreat,label=scales::percent(pct,accuracy=1))) +
  geom_col(position=position_dodge(.92)) +
  geom_text(position=position_dodge(.92),vjust=-.5,size=3,color="black") +
  scale_color_grey() +
  scale_fill_grey() +
  book_theme +
  scale_y_continuous(labels = scales::percent, limits=c(0,.42), expand = c(0,0)) +
  labs(x = "", y = "", fill = "",color="") +
  theme(legend.position="right")
p.clawback
savefig(p.clawback,"8.7_clawback_civicpulse", height = 2, filepath = "figures/")
